package org.icosagon.core.magic;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.bind.annotation.XmlElement;
import org.icosagon.core.math.Equation;
import org.icosagon.utils.Time;

/**
 * This class will keep track of how many charges an
 * object has.
 * @author Daniel Owens
 */
public class Charge {
    private Spell spell = null;
    private Time charges = null;
    private int uses = 0;

    public void setSpell(Spell spell) {
        this.spell = spell;
    }

    @XmlElement
    public Spell getSpell() {
        return this.spell;
    }

    /**
     * Sets the amount of charges this object is capable of
     * using during this alloted amount of <code>Time</code><br />
     * <b>NOTE:</b>It is highly suggested that you do not use any dice
     * rolls in the time's equation object. this may cause crazy behavior
     * when calculating the total number of charges there are.
     * @param equation
     */
    public void setCharges(Time equation) {
        this.charges = equation;
    }

    @XmlElement(name="total")
    public Time getCharges() {
        return this.charges;
    }

    /**
     * Adds a specified number of charges to this object. This
     * method is also used to remove subtract charges.
     * @param value - Number of charges to add.
     */
    public void addCharges(int value) {
        StringBuilder time = new StringBuilder(this.charges.getValue().getEquation());
        Pattern p = Pattern.compile("(\\+|\\-)\\d+$");
        Matcher m = p.matcher(time);
        if(m.find()) {
            String result = m.group();
            int change = Integer.parseInt(result.substring(1))+value;
            String insert = "";
            //If the result is a positive number this makes sure that the operator is prepended.
            if(change>=0)
                insert = "+";
            insert += String.valueOf(change);
            time.replace(m.start(), m.end(), insert);
        } else {
            time.append("+"+String.valueOf(value));
        }
        this.charges.setValue(new Equation(time.toString()));
    }

    /**
     * Re-sets the number of uses this charged object has had
     * back to 0.
     * @return
     */
    public void recharge() {
        this.uses = 0;
    }

    /**
     * Sets the number of times the charge has been used. <br />
     * If lower than zero then the uses is set to zero.
     * @param value
     */
    public void setUses(int value) {
        if(value < 0)
            value = 0;
        this.uses = value;
    }

    /**
     * This method will return the number of times this charge
     * has been used.
     * @return Number of uses.
     */
    @XmlElement(name="charges")
    public int getUses() {
        return this.uses;
    }
}